package org.xacmlauth.controller;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.xml.transform.StringSource;
import org.xacmlauth.core.domain.EnforceRespInfo;
import org.xacmlauth.core.domain.EnforceResponse;
import org.xacmlauth.form.UploadItem;
import org.xacmlauth.service.AuthClient;
import org.xacmlauth.service.AuthClientImpl;
import org.xacmlauth.util.ContextManager;

@Controller
@RequestMapping("/authRequest.html")
public class AuthRequestController {
	
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView enforce(UploadItem uploadItem, BindingResult result){
		ModelAndView model = new ModelAndView("AuthRequestForm");
		
		String clientID = uploadItem.getName();
		CommonsMultipartFile fileData = uploadItem.getFileData();
		
		if(clientID != null && fileData != null){
			try {
				AuthClient client = new AuthClientImpl();
				byte[] fileContent = fileData.getBytes();
				
				String authRequest = new String(fileContent, "UTF-8");
				String authResponse = client.authorize(clientID, authRequest);
				
				JAXBContext context = ContextManager.getDomainContext();
				Unmarshaller unmarshaller = context.createUnmarshaller();
				EnforceResponse enforceResponse = (EnforceResponse) unmarshaller.unmarshal(new StringReader(authResponse));
				
				EnforceRespInfo repsonseInfo = enforceResponse.getRespInfo();
				
				model = new ModelAndView("AuthRequestSuccess");
				model.addObject("authResponse", repsonseInfo.getResponse().getResults().get(0).getDecision());
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return model;
    }
     
	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute(new UploadItem());
		return "AuthRequestForm";
	}

}
